package com.limingru.newbee.service.impl;

import com.limingru.newbee.api.vo.CartItemVO;
import com.limingru.newbee.common.Constants;
import com.limingru.newbee.common.NewBeeMallException;
import com.limingru.newbee.common.ServiceResultEnum;
import com.limingru.newbee.dao.*;
import com.limingru.newbee.entity.*;
import com.limingru.newbee.service.OrderService;
import com.limingru.newbee.util.NumberUtil;
import com.limingru.newbee.util.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderAddressMapper orderAddressMapper;

    @Override
    public String saveOrder(List<CartItemVO> cartItemsForSettle, Address address, User user) {
        List<Long> cartItemIds = cartItemsForSettle.stream().map(CartItemVO::getCartItemId).collect(Collectors.toList());
        List<Long> goodsIds = cartItemsForSettle.stream().map(CartItemVO::getGoodsId).collect(Collectors.toList());
        List<Goods> goods = goodsMapper.selectGoodsByGoodsIds(goodsIds);
        // 检查是否有下架商品
        List<Goods> goodsNotSellingList = goods.stream().filter(Goods -> (int) Goods.getGoodsSellStatus() != Constants.GOODS_SELL_STATUS_UP)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(goodsNotSellingList)) {
            NewBeeMallException.fail(goodsNotSellingList.get(0).getGoodsName() + "已下架，无法生成订单");
        }
        // 删除购物项里的选中订单项
        if (cartMapper.deleteBatch(cartItemIds) > 0) {
            // 生成订单号
            String orderNo = NumberUtil.generateOrderNo();
            Order newOrder = new Order();
            newOrder.setOrderNo(orderNo);
            newOrder.setUserId(user.getUserId());
            // 计算总价
            int total = 0;
            for (CartItemVO c : cartItemsForSettle) {
                total += c.getSellingPrice() * c.getGoodsCount();
            }
            if (total < 1) {
                NewBeeMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getText());
            }
            newOrder.setTotalPrice(total);
            newOrder.setExtraInfo("");
            if (orderMapper.insertOrder(newOrder) > 0) {
                OrderAddress orderAddress = new OrderAddress();
                BeanUtils.copyProperties(address, orderAddress);
                orderAddress.setOrderId(newOrder.getOrderId());

                List<OrderItem> orderItemList = new ArrayList<>();
                for (CartItemVO c : cartItemsForSettle) {
                    OrderItem orderItem = new OrderItem();
                    BeanUtils.copyProperties(c, orderItem);
                    orderItem.setOrderId(newOrder.getOrderId());
                    orderItemList.add(orderItem);
                }

                if (orderItemMapper.insertBatch(orderItemList) > 0 && orderAddressMapper.insertOrderAddress(orderAddress) > 0) {
                    return orderNo;
                }
                return ServiceResultEnum.DB_ERROR.getText();
            }
            return ServiceResultEnum.DB_ERROR.getText();

        }
        return ServiceResultEnum.DB_ERROR.getText();
    }

    @Override
    public List<Order> orderList(Long userId) {
        return orderMapper.selectOrdersByUserId(userId);
    }

    @Override
    public Order orderDetail(List<Long> orderIds) {
        System.out.println(orderIds);
        List<Order> orderList = orderMapper.selectOrdersByOrderIds(orderIds);
        if (CollectionUtils.isEmpty(orderList)) {
            return null;
        }
        return orderList.get(0);
    }

    @Override
    public String deleteOrder(Order order) {
        int result = orderMapper.deleteOrder(order);
        if (result > 0) {
            return ServiceResultEnum.SUCCESS.getText();
        }
        return ServiceResultEnum.FAIL.getText();
    }
}
